import Cookies from "js-cookie"

export default{
    state:{
        isHold:false,
        tabList:[{
            path: "/",
            name: "home",
            label: "首页",
            icon: "s-home",
            url: "Home/Home",
        }],
        menu:[],

    },
    actions: {
        HoldMenu (context) {
          context.commit('HoldMenu')
        },
        clickMenu(context, value){
            console.log(context)
            context.commit('clickMenu', value)
        },
        deleteMenu(context, value){
            context.commit('deleteMenu', value)
        },
        SetMenuData(context, value){
            context.commit('SetMenuData', value)
        },
        SetMenuRouter(context, value){
            context.commit('SetMenuRouter', value)
        }
    },
    mutations:{
        HoldMenu(state){ 
            state.isHold = !state.isHold
        },
        clickMenu(state, value){
            console.log('clickMenu', value)
            if(value.name !=='home'){
                const index = state.tabList.findIndex(item=>item.name===value.name)
                if (index===-1){
                    state.tabList.push(value)
                }
            }
        },
        deleteMenu(state, value){
            console.log('delete', state, value)
            
            state.tabList.splice(value, 1)
        },
        SetMenuData(state, value){
            state.menu = value
            // vuex的数据保存在运行内存，刷新不会保留，需要缓存
            Cookies.set('menu', JSON.stringify(value))
        },
        // 动态注册路由
        SetMenuRouter(state, router){
            const cookie_data = JSON.parse(Cookies.get('menu'))
            if(!cookie_data) return
            state.menu = cookie_data
            // 动态路由
            const menuArray = []
            cookie_data.forEach(item => {
                if(item.children){
                    item.children = item.children.map(item=>{
                        item.component = ()=>import(`../views/${item.url}`)
                        return item
                    })
                    menuArray.push(...item.children)
                }else{
                    item.component = ()=>import(`../views/${item.url}`)
                    menuArray.push(item)
                }
            });
            // 动态添加
            menuArray.forEach(item=>{
                router.addRoute('main', item)
            })
        }

    },
}